package com.lagou.hive.utils;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;


public class HttpUtils {

    public static String httpGetUrl(String url, Map<String, String> map) {
        List<BasicNameValuePair> params = new ArrayList<>();
        if (Objects.isNull(map)) {
            return url;
        }
        Set<String> keys = map.keySet();
        for (String name : keys) {
            Object value = map.get(name);
            BasicNameValuePair nameValuePair = new BasicNameValuePair(name, value.toString());
            params.add(nameValuePair);
        }
        String queryString = URLEncodedUtils.format(params, "UTF-8");
        return url + "?" + queryString;
    }

    public static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";

    public static String httpGet(String url, Map parameters) {
        String response = null;
        int statusCode = 500;
        try {
            String _url = httpGetUrl(url, parameters);
            HttpGet get = new HttpGet(_url);
            get.setHeader(new BasicHeader(HTTP.USER_AGENT, USER_AGENT));
            RequestConfig config = RequestConfig.DEFAULT;
            HttpClient http = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
            HttpResponse httpResponse = http.execute(get);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                response = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException e) {
            System.out.println("请求url失败: " + url + " code:" + statusCode);
        }
        return response;
    }


}
